package edu.cmu.aes.project2.ws.data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import edu.cmu.aes.share.MySqlProperties;

public class UserInformationDao {
	private static String databaseLocation = MySqlProperties.getURL()+"/account";
	private static String userName = MySqlProperties.getUserName();
	private static String password = MySqlProperties.getPassword();

	private Connection getConnection() throws SQLException {
		Connection connection = null;

		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(databaseLocation,
					userName, password);
		} catch (Exception e) {
			throw new SQLException("Cannot instantiate database connector");
		}
		return connection;
	}

	public UserInformationDto getUserInformation(String userName) {
		Connection conn = null;
		try {
			conn = getConnection();
			PreparedStatement pstmnt = conn
					.prepareStatement("select * from account where username = ?");
			pstmnt.setString(1, userName);
			ResultSet result = pstmnt.executeQuery();
			if (result.next()) {
				UserInformationDto userInfo = new UserInformationDto();
				userInfo.setUserId(result.getInt("user_id"));
				userInfo.setUserName(userName);
				userInfo.setFirstName(result.getString("firstname"));
				userInfo.setLastName(result.getString("lastname"));
				userInfo.setAddress(result.getString("address"));
				userInfo.setCreditcard(result.getString("credit_card_no"));
				return userInfo;
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		}
		return null;
	}
	
	public Boolean authentication(String userName, String password){
		Connection conn = null;
		try {
			conn = getConnection();
			PreparedStatement pstmnt = conn
					.prepareStatement("select * from account where username = ? and password = ?");
			pstmnt.setString(1, userName);
			pstmnt.setString(2, password);
			ResultSet result = pstmnt.executeQuery();

			return result.next();
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}

			}
		}
		return null;
	}
}
